import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader } from '../components/UI/Card';
import { Badge } from '../components/UI/Badge';
import { Button } from '../components/UI/Button';
import { Modal } from '../components/UI/Modal';
import { ConfirmDialog } from '../components/UI/ConfirmDialog';
import { ToastContainer } from '../components/UI/Toast';
import { Pagination } from '../components/UI/Pagination';
import { useToast } from '../hooks/useToast';
import { mockApi } from '../services/mockApi';
import { api } from '../services/api';
import { Order, Product } from '../types';
import { 
  Plus,
  Search,
  Edit,
  Trash2,
  Package,
  User,
  Phone,
  Calendar,
  Hash,
  Eye,
  CheckCircle,
  Clock,
  AlertCircle,
  X,
  Minus,
  PackageX
} from 'lucide-react';

const statusConfig = {
  pending: { label: '待处理', variant: 'warning' as const, icon: Clock },
  processing: { label: '处理中', variant: 'info' as const, icon: Package },
  completed: { label: '已完成', variant: 'success' as const, icon: CheckCircle },
  cancelled: { label: '已取消', variant: 'error' as const, icon: AlertCircle },
};

// 修改为直接使用中文值
const orderTypeConfig = {
  '镇内订单': { label: '镇内订单', variant: 'primary' as const, color: 'bg-blue-100 text-blue-800' },
  '镇外订单': { label: '镇外订单', variant: 'secondary' as const, color: 'bg-purple-100 text-purple-800' },
};

interface OrderForm {
  userName: string;
  phone: string;
  orderType: '镇内订单' | '镇外订单'; // 直接使用中文值
  products: Array<{
    productId: string;
    productName: string;
    skuCode: string;
    rolls: number;
  }>;
}

interface SearchFilters {
  orderId: string;
  userName: string;
  phone: string;
  orderType: string;
}

export const Orders: React.FC = () => {
  const [orders, setOrders] = useState<Order[]>([]);
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedOrder, setSelectedOrder] = useState<Order | null>(null);
  const [editingOrder, setEditingOrder] = useState<Order | null>(null);
  const [deletingOrder, setDeletingOrder] = useState<Order | null>(null);
  
  // 模态框状态
  const [showOrderModal, setShowOrderModal] = useState(false);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [showEditModal, setShowEditModal] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  
  // 搜索状态
  const [searchFilters, setSearchFilters] = useState<SearchFilters>({
    orderId: '',
    userName: '',
    phone: '',
    orderType: ''
  });
  const [currentPage, setCurrentPage] = useState(1);
  const [totalOrders, setTotalOrders] = useState(0);
  
  // 表单状态
  const [orderForm, setOrderForm] = useState<OrderForm>({
    userName: '',
    phone: '',
    orderType: '镇内订单', // 默认使用中文值
    products: []
  });
  
  const [createLoading, setCreateLoading] = useState(false);
  const [editLoading, setEditLoading] = useState(false);
  const [deleteLoading, setDeleteLoading] = useState(false);
  const [searchLoading, setSearchLoading] = useState(false);

  const { toasts, removeToast, success, error, warning } = useToast();

  const pageSize = 10;

  // 初始加载数据
  useEffect(() => {
    fetchOrders();
    fetchProducts();
  }, [currentPage]);

  const fetchOrders = async (searchParams?: SearchFilters) => {
    try {
      setLoading(true);
      const params = searchParams || searchFilters;
      const result = await api.order.getOrders({
        page: currentPage,
        limit: 10,
        orderType: params.orderType || undefined,
        userName: params.userName || undefined,
        phone: params.phone || undefined,
        orderId: params.orderId || undefined,
      });
      setOrders(result.data);
      setTotalOrders(result.total);
    } catch (err) {
      console.error('获取订单列表失败:', err);
      error('获取订单列表失败', err instanceof Error ? err.message : '获取订单列表失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchProducts = async () => {
    try {
      // 使用货物API获取产品列表
      const result = await api.cargo.getCargos({ limit: 100 });
      const productsFromCargo = result.data.map(cargo => ({
        id: cargo.id,
        name: cargo.name,
        skuCode: cargo.id, // 使用id作为skuCode
        unit: cargo.unit,
        unitPrice: 0, // 后端没有价格信息
        stock: 0, // 后端没有库存信息
        createdAt: cargo.createdAt,
        updatedAt: cargo.updatedAt,
      }));
      setProducts(productsFromCargo);
    } catch (err) {
      console.error('获取产品列表失败:', err);
      error('获取产品列表失败', err instanceof Error ? err.message : '获取产品列表失败');
    }
  };

  // 处理搜索输入变化（不触发请求）
  const handleSearchChange = (field: keyof SearchFilters, value: string) => {
    setSearchFilters(prev => ({
      ...prev,
      [field]: value
    }));
  };

  // 执行搜索
  const handleSearch = async () => {
    try {
      setSearchLoading(true);
      setCurrentPage(1); // 重置到第一页
      await fetchOrders(searchFilters);
    } finally {
      setSearchLoading(false);
    }
  };

  // 清空搜索并重新获取数据
  const clearSearch = async () => {
    const emptyFilters = {
      orderId: '',
      userName: '',
      phone: '',
      orderType: ''
    };
    setSearchFilters(emptyFilters);
    setCurrentPage(1);
    await fetchOrders(emptyFilters);
  };

  // 检查是否有搜索条件
  const hasSearchFilters = Object.values(searchFilters).some(value => value.trim() !== '');

  const totalPages = Math.ceil(totalOrders / pageSize);

  // 重置表单
  const resetOrderForm = () => {
    setOrderForm({
      userName: '',
      phone: '',
      orderType: '镇内订单', // 使用中文值
      products: []
    });
  };

  // 添加产品到订单
  const addProductToOrder = () => {
    setOrderForm(prev => ({
      ...prev,
      products: [...prev.products, {
        productId: '',
        productName: '',
        skuCode: '',
        rolls: 1
      }]
    }));
  };

  // 移除产品
  const removeProductFromOrder = (index: number) => {
    setOrderForm(prev => ({
      ...prev,
      products: prev.products.filter((_, i) => i !== index)
    }));
  };

  // 更新产品信息
  const updateOrderProduct = (index: number, field: string, value: any) => {
    setOrderForm(prev => ({
      ...prev,
      products: prev.products.map((product, i) => {
        if (i === index) {
          if (field === 'productId') {
            const selectedProduct = products.find(p => p.id === value);
            return {
              ...product,
              productId: value,
              productName: selectedProduct?.name || '',
              skuCode: selectedProduct?.skuCode || ''
            };
          }
          return { ...product, [field]: value };
        }
        return product;
      })
    }));
  };

  // 计算总出库量
  const calculateTotalRolls = () => {
    return orderForm.products.reduce((sum, product) => sum + (product.rolls || 0), 0);
  };

  // 处理查看订单
  const handleViewOrder = async (order: Order) => {
    try {
      setSelectedOrder(order);
      setShowOrderModal(true);
      
      // 调用后端接口获取订单详情（产品信息）
      const orderDetails = await api.order.getOrderDetails(order.id);
      
      // 将后端返回的订单详情转换为前端格式
      const products = orderDetails.map(detail => ({
        id: detail.skuCode.toString(),
        orderId: order.id,
        productId: detail.skuCode.toString(),
        productName: detail.productName,
        skuCode: detail.skuCode.toString(),
        rolls: detail.rolls,
        unitPrice: 0, // 后端没有价格信息
        totalPrice: 0, // 后端没有价格信息
      }));
      
      // 更新订单的产品信息
      setSelectedOrder({
        ...order,
        products: products
      });
      
    } catch (err) {
      console.error('获取订单详情失败:', err);
      error('获取订单详情失败', err instanceof Error ? err.message : '获取订单详情失败');
      // 即使获取详情失败，也显示基本信息
      setSelectedOrder(order);
      setShowOrderModal(true);
    }
  };

  // 处理编辑订单
  const handleEditOrder = (order: Order) => {
    setEditingOrder(order);
    
    // 只设置基本信息，不需要获取产品详情
    setOrderForm({
      userName: order.userName,
      phone: order.phone,
      orderType: order.orderType,
      products: [] // 编辑时不处理产品清单
    });
    
    setShowEditModal(true);
  };

  // 处理删除订单
  const handleDeleteOrder = (order: Order) => {
    setDeletingOrder(order);
    setShowDeleteDialog(true);
  };

  // 处理创建订单
  const handleCreateOrder = async () => {
    try {
      setCreateLoading(true);

      // 验证表单
      if (!orderForm.userName.trim()) {
        error('表单验证失败', '请输入客户姓名');
        return;
      }

      if (!orderForm.phone.trim()) {
        error('表单验证失败', '请输入客户手机号');
        return;
      }

      if (orderForm.products.length === 0) {
        error('表单验证失败', '请至少添加一个货物');
        return;
      }

      // 验证产品
      for (const product of orderForm.products) {
        if (!product.productId) {
          error('表单验证失败', '请选择货物');
          return;
        }
        if (product.rolls <= 0) {
          error('表单验证失败', '出库量必须大于0');
          return;
        }
      }

      const totalRolls = calculateTotalRolls();

      const newOrder = {
        userName: orderForm.userName.trim(),
        phone: orderForm.phone.trim(),
        totalRolls,
        orderType: orderForm.orderType,
        orderDate: new Date().toISOString().split('T')[0],
        orderTime: new Date().toTimeString().slice(0, 5),
        status: 'completed' as const,
        products: orderForm.products.map(p => ({
          id: Date.now().toString() + Math.random().toString(),
          orderId: '', // 会在创建后设置
          productId: p.productId,
          productName: p.productName,
          skuCode: p.skuCode,
          rolls: p.rolls,
          unitPrice: 0, // 暂时设为0
          totalPrice: 0, // 暂时设为0
        })),
        notes: '',
      };

      await api.order.createOrder(newOrder);

      success('订单创建成功', '新订单已成功创建');
      resetOrderForm();
      setShowCreateModal(false);
      await fetchOrders();

    } catch (err) {
      console.error('创建订单失败:', err);
      error('创建订单失败', err instanceof Error ? err.message : '创建订单失败');
    } finally {
      setCreateLoading(false);
    }
  };

  // 处理保存编辑
  const handleSaveEdit = async () => {
    if (!editingOrder) return;

    try {
      setEditLoading(true);

      // 验证表单 - 只验证基本信息
      if (!orderForm.userName.trim()) {
        error('表单验证失败', '请输入客户姓名');
        return;
      }

      if (!orderForm.phone.trim()) {
        error('表单验证失败', '请输入客户手机号');
        return;
      }

      // 构建更新数据 - 只包含基本信息
      const updates = {
        userName: orderForm.userName.trim(),
        phone: orderForm.phone.trim(),
        orderType: orderForm.orderType,
        orderDate: editingOrder.orderDate,
        orderTime: editingOrder.orderTime,
      };

      await api.order.updateOrder(editingOrder.id, updates);

      success('订单更新成功', '订单基本信息已成功更新');
      resetOrderForm();
      setEditingOrder(null);
      setShowEditModal(false);
      await fetchOrders();

    } catch (err) {
      console.error('更新订单失败:', err);
      error('更新订单失败', err instanceof Error ? err.message : '更新订单失败');
    } finally {
      setEditLoading(false);
    }
  };

  // 确认删除
  const confirmDelete = async () => {
    if (!deletingOrder) return;

    try {
      setDeleteLoading(true);
      
      const result = await api.order.deleteOrder(deletingOrder.id);
      
      if (result) {
        success('订单删除成功', `订单 ${deletingOrder.orderNumber} 已成功删除`);
        await fetchOrders();
      } else {
        error('删除失败', '删除订单失败');
      }
    } catch (err) {
      console.error('删除订单失败:', err);
      error('删除失败', err instanceof Error ? err.message : '删除订单失败');
    } finally {
      setDeleteLoading(false);
      setDeletingOrder(null);
      setShowDeleteDialog(false);
    }
  };

  return (
    <div className="space-y-6 animate-slide-up">
      {/* Toast 通知容器 */}
      <ToastContainer toasts={toasts} onClose={removeToast} />

      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-gray-800">订单管理</h1>
          <p className="text-gray-600">管理所有订单的创建、跟踪和处理</p>
        </div>
        <Button onClick={() => setShowCreateModal(true)} icon={<Plus className="w-4 h-4" />}>
          新建订单
        </Button>
      </div>

      {/* 搜索筛选器 */}
      <Card>
        <CardContent className="p-6">
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <h3 className="text-lg font-medium text-gray-800">搜索筛选</h3>
              <div className="flex items-center space-x-2">
                {hasSearchFilters && (
                  <Button
                    variant="ghost"
                    size="sm"
                    icon={<X className="w-4 h-4" />}
                    onClick={clearSearch}
                    className="text-gray-500 hover:text-gray-700"
                  >
                    清空搜索
                  </Button>
                )}
                <Button
                  variant="outline"
                  size="sm"
                  icon={<Search className="w-4 h-4" />}
                  onClick={handleSearch}
                  loading={searchLoading}
                  className="text-primary-600 border-primary-200 hover:bg-primary-50"
                >
                  搜索
                </Button>
              </div>
            </div>
            
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
              {/* 订单号搜索 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  订单号
                </label>
                <div className="relative">
                  <Hash className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
                  <input
                    type="text"
                    placeholder="输入订单号..."
                    className="w-full pl-10 pr-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-all duration-200"
                    value={searchFilters.orderId}
                    onChange={(e) => handleSearchChange('orderId', e.target.value)}
                    onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
                  />
                </div>
              </div>

              {/* 客户姓名搜索 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  客户姓名
                </label>
                <div className="relative">
                  <User className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
                  <input
                    type="text"
                    placeholder="输入客户姓名..."
                    className="w-full pl-10 pr-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-all duration-200"
                    value={searchFilters.userName}
                    onChange={(e) => handleSearchChange('userName', e.target.value)}
                    onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
                  />
                </div>
              </div>

              {/* 手机号搜索 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  手机号
                </label>
                <div className="relative">
                  <Phone className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
                  <input
                    type="text"
                    placeholder="输入手机号..."
                    className="w-full pl-10 pr-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-all duration-200"
                    value={searchFilters.phone}
                    onChange={(e) => handleSearchChange('phone', e.target.value)}
                    onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
                  />
                </div>
              </div>

              {/* 订单类型搜索 - 修改为使用中文值 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  订单类型
                </label>
                <select
                  className="w-full px-3 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-all duration-200"
                  value={searchFilters.orderType}
                  onChange={(e) => handleSearchChange('orderType', e.target.value)}
                >
                  <option value="">全部类型</option>
                  <option value="镇内订单">镇内订单</option>
                  <option value="镇外订单">镇外订单</option>
                </select>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 订单列表 */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <h2 className="text-lg font-semibold text-gray-800">订单列表</h2>
            <Badge variant="info">{orders.length} 个订单</Badge>
          </div>
        </CardHeader>
        <CardContent className="p-0">
          {loading ? (
            <div className="p-6">
              <div className="space-y-4">
                {Array.from({ length: 5 }).map((_, i) => (
                  <div key={i} className="flex items-center space-x-4 animate-pulse">
                    <div className="w-16 h-16 bg-gray-200 rounded-xl"></div>
                    <div className="flex-1 space-y-2">
                      <div className="h-4 bg-gray-200 rounded w-1/4"></div>
                      <div className="h-3 bg-gray-200 rounded w-1/2"></div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          ) : (
            <>
              <div className="divide-y divide-gray-100">
                {orders.map((order) => {
                  const statusInfo = statusConfig[order.status];
                  const orderTypeInfo = orderTypeConfig[order.orderType as keyof typeof orderTypeConfig] || {
                    label: order.orderType,
                    variant: 'secondary' as const,
                    color: 'bg-gray-100 text-gray-800'
                  };
                  const StatusIcon = statusInfo.icon;
                  
                  return (
                    <div 
                      key={order.id} 
                      className="p-6 hover:bg-gray-50 transition-colors duration-200 cursor-pointer"
                      onClick={() => handleViewOrder(order)}
                    >
                      <div className="flex items-center justify-between">
                        <div className="flex items-center space-x-4">
                          <div className="w-12 h-12 bg-gradient-to-br from-primary-100 to-secondary-100 rounded-xl flex items-center justify-center">
                            <Package className="w-6 h-6 text-primary-600" />
                          </div>
                          <div>
                            <div className="flex items-center space-x-2 mb-1">
                              <h3 className="font-semibold text-gray-800">订单 {order.orderNumber}</h3>
                              <Badge variant={statusInfo.variant} className="flex items-center space-x-1">
                                <StatusIcon className="w-3 h-3" />
                                <span>{statusInfo.label}</span>
                              </Badge>
                              <span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${orderTypeInfo.color}`}>
                                {orderTypeInfo.label}
                              </span>
                            </div>
                            <div className="flex items-center space-x-4 text-sm text-gray-600">
                              <div className="flex items-center space-x-1">
                                <User className="w-4 h-4" />
                                <span>{order.userName}</span>
                              </div>
                              <div className="flex items-center space-x-1">
                                <Phone className="w-4 h-4" />
                                <span>{order.phone}</span>
                              </div>
                              <div className="flex items-center space-x-1">
                                <Calendar className="w-4 h-4" />
                                <span>{order.orderDate} {order.orderTime}</span>
                              </div>
                              <div className="flex items-center space-x-1">
                                <Package className="w-4 h-4" />
                                <span>出库量: {order.totalRolls}</span>
                              </div>
                            </div>
                          </div>
                        </div>
                        <div className="flex items-center space-x-2">
                          <Button 
                            variant="ghost" 
                            size="sm" 
                            icon={<Eye className="w-4 h-4" />}
                            onClick={(e) => {
                              e.stopPropagation();
                              handleViewOrder(order);
                            }}
                          >
                            查看
                          </Button>
                          <Button 
                            variant="ghost" 
                            size="sm" 
                            icon={<Edit className="w-4 h-4" />}
                            onClick={(e) => {
                              e.stopPropagation();
                              handleEditOrder(order);
                            }}
                          >
                            编辑
                          </Button>
                          <Button 
                            variant="ghost" 
                            size="sm" 
                            icon={<Trash2 className="w-4 h-4" />}
                            onClick={(e) => {
                              e.stopPropagation();
                              handleDeleteOrder(order);
                            }}
                            className="text-error-600 hover:text-error-700 hover:bg-error-50"
                          >
                            删除
                          </Button>
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>

              {/* 分页 */}
              <Pagination
                currentPage={currentPage}
                totalPages={totalPages}
                totalItems={totalOrders}
                onPageChange={setCurrentPage}
                className="p-6 border-t border-gray-100"
              />
            </>
          )}
        </CardContent>
      </Card>

      {/* 订单详情模态框 */}
      <Modal
        isOpen={showOrderModal}
        onClose={() => setShowOrderModal(false)}
        title="订单详情"
        size="lg"
      >
        {selectedOrder && (
          <div className="space-y-6">
            {/* 基本信息 */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="space-y-4">
                <div>
                  <label className="text-sm font-medium text-gray-600">订单号</label>
                  <p className="text-lg font-semibold text-gray-800">{selectedOrder.orderNumber}</p>
                </div>
                <div>
                  <label className="text-sm font-medium text-gray-600">用户信息</label>
                  <div className="space-y-2">
                    <div className="flex items-center space-x-2">
                      <User className="w-4 h-4 text-gray-500" />
                      <span className="text-gray-800">{selectedOrder.userName}</span>
                    </div>
                    <div className="flex items-center space-x-2">
                      <Phone className="w-4 h-4 text-gray-500" />
                      <span className="text-gray-800">{selectedOrder.phone}</span>
                    </div>
                  </div>
                </div>
                <div>
                  <label className="text-sm font-medium text-gray-600">订单类型</label>
                  <div className="mt-1">
                    {(() => {
                      const orderTypeInfo = orderTypeConfig[selectedOrder.orderType as keyof typeof orderTypeConfig] || {
                        label: selectedOrder.orderType,
                        variant: 'secondary' as const,
                        color: 'bg-gray-100 text-gray-800'
                      };
                      return (
                        <span className={`inline-flex items-center px-3 py-1 rounded-full text-sm font-medium ${orderTypeInfo.color}`}>
                          {orderTypeInfo.label}
                        </span>
                      );
                    })()}
                  </div>
                </div>
              </div>
              <div className="space-y-4">
                <div>
                  <label className="text-sm font-medium text-gray-600">订单状态</label>
                  <div className="mt-1">
                    <Badge variant={statusConfig[selectedOrder.status].variant}>
                      {statusConfig[selectedOrder.status].label}
                    </Badge>
                  </div>
                </div>
                <div>
                  <label className="text-sm font-medium text-gray-600">下单时间</label>
                  <div className="flex items-center space-x-2 text-gray-800">
                    <Calendar className="w-4 h-4 text-gray-500" />
                    <span>{selectedOrder.orderDate} {selectedOrder.orderTime}</span>
                  </div>
                </div>
                <div>
                  <label className="text-sm font-medium text-gray-600">总出库量</label>
                  <p className="text-lg font-semibold text-primary-600">{selectedOrder.totalRolls}</p>
                </div>
              </div>
            </div>

            {/* 产品列表 */}
            <div>
              <label className="text-sm font-medium text-gray-600 mb-3 block">产品明细</label>
              <div className="border border-gray-200 rounded-lg overflow-hidden">
                <table className="w-full">
                  <thead className="bg-gray-50">
                    <tr>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">产品名称</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">SKU编码</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">出库量</th>
                    </tr>
                  </thead>
                  <tbody className="bg-white divide-y divide-gray-200">
                    {selectedOrder.products.map((product, index) => (
                      <tr key={index}>
                        <td className="px-4 py-4 whitespace-nowrap text-sm text-gray-900">{product.productName}</td>
                        <td className="px-4 py-4 whitespace-nowrap text-sm text-gray-500">{product.skuCode}</td>
                        <td className="px-4 py-4 whitespace-nowrap text-sm text-gray-900">{product.rolls}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        )}
      </Modal>

      {/* 新建订单模态框 */}
      <Modal
        isOpen={showCreateModal}
        onClose={() => {
          setShowCreateModal(false);
          resetOrderForm();
        }}
        title="新建订单"
        size="lg"
      >
        <div className="space-y-6">
          {/* 基本信息 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                客户姓名 <span className="text-error-500">*</span>
              </label>
              <input
                type="text"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                value={orderForm.userName}
                onChange={(e) => setOrderForm(prev => ({ ...prev, userName: e.target.value }))}
                placeholder="请输入客户姓名"
                required
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                客户手机号 <span className="text-error-500">*</span>
              </label>
              <input
                type="tel"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                value={orderForm.phone}
                onChange={(e) => setOrderForm(prev => ({ ...prev, phone: e.target.value }))}
                placeholder="请输入客户手机号"
                required
              />
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-1 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">订单类型</label>
              <select 
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                value={orderForm.orderType}
                onChange={(e) => setOrderForm(prev => ({ ...prev, orderType: e.target.value as any }))}
              >
                <option value="镇内订单">镇内订单</option>
                <option value="镇外订单">镇外订单</option>
              </select>
            </div>
          </div>

          {/* 产品列表 */}
          <div>
            <div className="flex items-center justify-between mb-3">
              <label className="block text-sm font-medium text-gray-700">
                产品清单 <span className="text-error-500">*</span>
              </label>
              <Button 
                size="sm" 
                icon={<Plus className="w-4 h-4" />}
                onClick={addProductToOrder}
              >
                添加产品
              </Button>
            </div>
            
            {orderForm.products.length === 0 ? (
              <div className="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center">
                <PackageX className="w-12 h-12 text-gray-400 mx-auto mb-4" />
                <p className="text-gray-500">暂无产品，点击"添加产品"开始添加</p>
              </div>
            ) : (
              <div className="space-y-3">
                {orderForm.products.map((product, index) => (
                  <div key={index} className="flex items-center space-x-3 p-3 border border-gray-200 rounded-lg">
                    <div className="flex-1 grid grid-cols-1 md:grid-cols-3 gap-3">
                      <div>
                        <select
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent text-sm"
                          value={product.productId}
                          onChange={(e) => updateOrderProduct(index, 'productId', e.target.value)}
                        >
                          <option value="">选择产品</option>
                          {products.map(p => (
                            <option key={p.id} value={p.id}>
                              {p.name} ({p.skuCode})
                            </option>
                          ))}
                        </select>
                      </div>
                      <div>
                        <input
                          type="number"
                          min="1"
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent text-sm"
                          value={product.rolls}
                          onChange={(e) => updateOrderProduct(index, 'rolls', parseInt(e.target.value) || 0)}
                          placeholder="出库量"
                        />
                      </div>
                      <div className="flex items-center text-sm text-gray-600">
                        <span>SKU: {product.skuCode || '未选择'}</span>
                      </div>
                    </div>
                    <Button
                      variant="ghost"
                      size="sm"
                      icon={<Minus className="w-4 h-4" />}
                      onClick={() => removeProductFromOrder(index)}
                      className="text-error-600 hover:text-error-700 hover:bg-error-50"
                    >
                      删除
                    </Button>
                  </div>
                ))}
                <div className="text-right pt-2 border-t border-gray-200">
                  <span className="text-sm font-medium text-gray-700">
                    总出库量: <span className="text-primary-600 font-semibold">{calculateTotalRolls()}</span>
                  </span>
                </div>
              </div>
            )}
          </div>

          {/* 操作按钮 */}
          <div className="flex justify-end space-x-3 pt-4 border-t border-gray-200">
            <Button
              variant="outline"
              onClick={() => {
                setShowCreateModal(false);
                resetOrderForm();
              }}
              disabled={createLoading}
            >
              取消
            </Button>
            <Button
              onClick={handleCreateOrder}
              loading={createLoading}
            >
              创建订单
            </Button>
          </div>
        </div>
      </Modal>

      {/* 编辑订单模态框 */}
      <Modal
        isOpen={showEditModal}
        onClose={() => {
          setShowEditModal(false);
          setEditingOrder(null);
          resetOrderForm();
        }}
        title="编辑订单"
        size="md"
      >
        <div className="space-y-6">
          {/* 基本信息 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                客户姓名 <span className="text-error-500">*</span>
              </label>
              <input
                type="text"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                value={orderForm.userName}
                onChange={(e) => setOrderForm(prev => ({ ...prev, userName: e.target.value }))}
                placeholder="请输入客户姓名"
                required
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                客户手机号 <span className="text-error-500">*</span>
              </label>
              <input
                type="tel"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                value={orderForm.phone}
                onChange={(e) => setOrderForm(prev => ({ ...prev, phone: e.target.value }))}
                placeholder="请输入客户手机号"
                required
              />
            </div>
          </div>

          <div className="grid grid-cols-1 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">订单类型</label>
              <select 
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                value={orderForm.orderType}
                onChange={(e) => setOrderForm(prev => ({ ...prev, orderType: e.target.value as any }))}
              >
                <option value="镇内订单">镇内订单</option>
                <option value="镇外订单">镇外订单</option>
              </select>
            </div>
          </div>

          {/* 提示信息 */}
          <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
            <div className="flex items-center">
              <div className="flex-shrink-0">
                <Package className="w-5 h-5 text-blue-400" />
              </div>
              <div className="ml-3">
                <p className="text-sm text-blue-700">
                  <span className="font-medium">注意：</span>
                  编辑订单只能修改客户信息和订单类型，产品清单无法修改。如需修改产品，请删除订单重新创建。
                </p>
              </div>
            </div>
          </div>

          {/* 操作按钮 */}
          <div className="flex justify-end space-x-3 pt-4 border-t border-gray-200">
            <Button
              variant="outline"
              onClick={() => {
                setShowEditModal(false);
                setEditingOrder(null);
                resetOrderForm();
              }}
              disabled={editLoading}
            >
              取消
            </Button>
            <Button
              onClick={handleSaveEdit}
              loading={editLoading}
            >
              保存修改
            </Button>
          </div>
        </div>
      </Modal>

      {/* 删除确认对话框 */}
      <ConfirmDialog
        isOpen={showDeleteDialog}
        onClose={() => {
          setShowDeleteDialog(false);
          setDeletingOrder(null);
        }}
        onConfirm={confirmDelete}
        title="删除订单"
        message={`确定要删除订单 "${deletingOrder?.orderNumber}" 吗？此操作不可撤销。`}
        confirmText="确认删除"
        cancelText="取消"
        type="danger"
        loading={deleteLoading}
      />
    </div>
  );
};